'''
#1
# use list datastruct
from commonfuncs import primefunctools as pf
pt = pf.primesTable(6)
def isPrime(n):
    try:
        return pt[n]
    except ValueError:
        return pf.isPrime(n)

#2
# use dict datastruct
from commonfuncs import primefunctools as pf
pf.generatePrimeDict(6)
with open("./commonfuncs/Primes6.dict", 'rb') as pfile:
    pd = pickle.load(pfile)

#3
# Primes.dict exists in which number < 10^6 defualt.
import pickle
with open("./commonfuncs/Primes6.dict", 'rb') as pfile:
    pd = pickle.load(pfile)

#4
# just need little times prime testing
from commonfuncs import primefunctools as pf
pf.isPrime()
'''



def primesTable(d: int = 6):
    lens = 10**d
    primesT = [True]*lens
    primesT[0], primesT[1], primesT[2] = False, False, True

    for n in range(4, 10**d,2):
        primesT[n] = False

    for n in range(3, 10**d,2):
        for k in range(n, (lens-1)//n+1):
            primesT[n*k] = False

    # print(f'Primes(<{lens}) is ready.')
    return primesT

def generatePrimeDict(d:int = 6):
    import pickle
    pt = primesTable(d)

    primesdict = {n:pt[n] for n in range(10**d)}
    with open(f"./commonfuncs/Primes{d}.dict", 'wb') as pfile:
        pickle.dump(primesdict,pfile)
    
    return 



def isPrime(n: int) -> bool:
    '''
    >>> assert all(list(map(isPrime, [2,3,5,7,11,13])))
    >>> assert not any(list(map(isPrime, [0,1,4,6,8,9])))
    '''

    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    n_sqrt = n**0.5
    if int(n_sqrt) == n_sqrt:
        return False

    for i in range(3, int(n_sqrt)+1, 2):
        if n % i == 0:
            return False
    return True

if __name__ == '__main__':
    print('isPrime:\n',[n for n in range(100) if isPrime(n)])

    import pickle
    pt = primesTable(3)
    print('primesTable:\n' ,[n for n in range(100) if pt[n]] ,'...')

    generatePrimeDict(6)
    #with open("./commonfuncs/Primes6.dict", 'rb') as pfile:
    #    pd = pickle.load(pfile) 
    #print(pd)

